package com.zang.im.croom.netty.processor;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.googlecode.protobuf.format.JsonFormat;
import com.zang.im.croom.model.protobuf.WSMessageOuterClass;
import com.zang.im.croom.netty.handler.websocket.TextHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Handler 分发器 处理请求
 *
 * @author Zhang Qiang
 * @Date 2019/7/29 17:07
 */
@Slf4j
@Component
public class WebSocketProcessor {

    @Autowired
    private TextHandler textHandler;


    public void handler(ChannelHandlerContext ctx, Map<String, Channel> channelMap, TextWebSocketFrame msg){
        String text = msg.text();
        String msgTypeName = "msgType";
        log.info("TextWebSocketFrame : " + text.toString());

        if (!text.isEmpty()){

                try {
                    System.out.println(text);
                    JSONObject json  = JSONUtil.parseObj(text);
                    log.info("json: " + json.toString());
                    if ( json.get(msgTypeName) != null ){
                        String jsonFormat = JSONUtil.toJsonStr(json);
                        WSMessageOuterClass.WSMessage.Builder wsMessageBuilder = WSMessageOuterClass.WSMessage.newBuilder();
                        try {
                            JsonFormat.merge(jsonFormat, wsMessageBuilder);
                        } catch (Exception e){
                            e.printStackTrace();
                            log.info("参数： " + jsonFormat);
                            log.error("Json转换ProtoBuf失败");
                        }
                        WSMessageOuterClass.WSMessage wsMessage =  wsMessageBuilder.build();
                        int msgType = wsMessage.getMsgType();
                        log.info("message type : " + msgType);
                        if (msgType != 0){
                            switch (msgType){
                                case 1000 :
                                    textHandler.handleMsg(ctx,channelMap, wsMessage);
                                    break;
                                default:
                                    break;
                            }
                        }

                    }

                } catch ( JSONException j){
                    log.info("消息非Json格式！：" + text);
                    ctx.channel().writeAndFlush("参数传入错误！");
                }

        }

    }


}
